﻿#include"XQPandasReadCSV.h"
#include<QTextCodec>
#include<QFile>
#include<QFileInfo>
#include<QDebug>
XQPandasReadCSV::XQPandasReadCSV(const QString& local, const QString& coding)
{
	readfile(local,coding);
}

bool XQPandasReadCSV::readfile(const QString& path, const QString& coding)
{
	m_codec = QTextCodec::codecForName(coding.toLocal8Bit().data());
	m_path = path;
	return QFile(path).exists();
	/*m_codec->toUnicode(file->readLine());*/
}

XQPandasReadCSV::read_csv_iterator XQPandasReadCSV::begin()
{
	return read_csv_iterator(m_path,m_codec);
}

XQPandasReadCSV::read_csv_iterator XQPandasReadCSV::end()
{
	return read_csv_iterator(m_path, m_codec,QFile(m_path).size());
}

XQPandasReadCSV::read_csv_iterator::read_csv_iterator()
{
}

XQPandasReadCSV::read_csv_iterator::read_csv_iterator(const QString& path, QTextCodec* codec, qint64 pos)
	:m_file(path),m_codec(codec),m_pos(pos)
{
	if(m_file.exists()&&m_file.open(QFile::ReadOnly | QFile::Text))
	{
		m_file.seek(pos);
		/*m_end = false;*/
		++(*this);
	}
}

QString XQPandasReadCSV::read_csv_iterator::filePath()const
{
	return QFileInfo(m_file).filePath();
}

XQPandasItem& XQPandasReadCSV::read_csv_iterator::operator*()
{
	if (m_file.atEnd())
		m_end = true;
	return m_buffLine;
}

XQPandasReadCSV::read_csv_iterator XQPandasReadCSV::read_csv_iterator::operator++(int)
{
	if(m_file.atEnd())
		return XQPandasReadCSV::read_csv_iterator(filePath(), m_codec, m_pos);
	++(*this);
	return read_csv_iterator(filePath(), m_codec, m_pos);
}

XQPandasReadCSV::read_csv_iterator& XQPandasReadCSV::read_csv_iterator::operator++()
{
	while (!m_file.atEnd())
	{//去除空的行
		auto text = m_file.readLine();
		if (text.isEmpty())
			continue;
		if (m_codec)
			m_buffLine = XQPandasItem(m_codec->toUnicode(text).split(","));
		else
			m_buffLine = XQPandasItem(QString(text).split(","));
		break;
	}
	
	m_pos = m_file.pos();
	return *this;
}

bool XQPandasReadCSV::read_csv_iterator::operator==(const read_csv_iterator& other) const
{
	return (filePath() == other.filePath()) && (m_pos == other.m_pos) && (m_end == other.m_end);
}

bool XQPandasReadCSV::read_csv_iterator::operator!=(const read_csv_iterator& other) const
{
	return (m_pos != other.m_pos)||(m_end==other.m_end) || (filePath() != other.filePath());
}
